#!/usr/bin/perl

sub server_list(){
	my $re;
	my @servers=open_server();
	foreach(@servers){
		my @elements = split (/\|/, $_);
		my $ssize=$elements[2];
		my $sname=$elements[0];
		my $sfile=$elements[1];
		$re.="$sname  Total:".get_space($sname). " Used: ". used_space($sname);
		$re.="<br>\n";
	}
	return $re;

}
sub open_server()
{
	my ($key)=@_;
	$key=~ s/\-//g;
	$key=~ s/\n//g;
	$key=~ s/\r//g;
	my @files;
	my $i=0;
	open(FH, "server.config");
	while(<FH>){
		next if /^\#/;
		my $line=$_;
		s/\///g;
		s/\-//g;
		$files[$i++]=$line if /$key/ or not $key;
	}	
	close FH;
	return @files;
}

sub free_space(){
	my $size=0;
	my @servers=open_server();
	foreach(@servers){
		my @elements = split (/\|/, $_);
		my $ssize=$elements[2];
		my $sname=$elements[0];
		my $sfile=$elements[1];
		$size += - used_space($sname) + get_space($sname);
	}
	return $size;

}
sub choose_server(){

	my ($size)=@_;
	my @servers=open_server();
	my $i=0;
	foreach(@servers){

		my $line=$_;

		$i++;
		my @elements = split (/\|/, $_);
		my $sname=$elements[0];
		my $sfile=$elements[1];
		my $ssize=$elements[2];
#		if($size + used_space($sname) < get_space($sname)){
		if($size + used_space($sname) < $ssize){
			return ($sfile,$sname);
		}
	}

	return "./index_cn.cgi";
}


sub record_message(){

my($g_id,$name,$content,$file)=@_;

return 0 if not $content;

my ($sec,$min,$hour,$mday,$mon,$year, $wday,$yday,$isdst) = localtime time;
$year=$year-100+2000;
$mon=$mon+1;
my $mdate=$year."/".$mon."/".$mday."  ".$hour.":".$min;

#if(-e "./message/${g_id}.txt"){
#
if(-e "./message/${g_id}.txt")
{
open(SENDMAIL, ">>./message/${g_id}.txt") or die "Cannot open txt: $!";
}
else
{
open(SENDMAIL, ">./message/${g_id}.txt") or die "Cannot open txt: $!";
}
print SENDMAIL "[Message Begin]\n";
print SENDMAIL "[From]".$name."\n";
print SENDMAIL "[File]".$file."\n";
print SENDMAIL "[Content Begin]\n";
print SENDMAIL $content;
print SENDMAIL "\n";
print SENDMAIL "[Content End]\n";
print SENDMAIL "[Date] $mdate\n";
print SENDMAIL "[Message End]\n";
print SENDMAIL "--------------------------------------\n";
close(SENDMAIL);
#}

}

sub read_message(){

my ($g_id,$start)= @_;


my ($in_m,$in_cont,$m_from,$m_date,$m_cont,$m_file,@msg_list,$final_str,$num,$new_start);
$num=0;
open( IN, "<./message/${g_id}.txt");
while(<IN>)
{
        my $line=$_;
        chop($line);
        if ($line=~/\[Message Begin\]/) {
                $in_m=1;
                $line="";
                next;
        }
        if ($line=~/^\[Message End\]/)
        {
                $in_m=0;
                if( not $m_cont=~/mao\@ustc.edu.cn/ and not $m_cont eq "") {
                	            	
                        $msg_list[$num]=m_output($num,$m_from,$m_date,$m_cont).$final_str if not $simple;
                        $num++;

                }
                $m_cont="";
                $line="";
                next;
        }
        if ($line=~/^\[Content End\]/) {
                $in_cont=0 ;
                $line="";
                next;
        }
        if($in_cont==1) {
                $m_cont.=$line;
                $line="";
                next;
        }

        if($in_m == 1) {
                $m_from=$1 if $line=~/^\[From\](.*)/;
                $m_date=$1 if $line=~/^\[Date\](.*)/;
                $m_file=$1 if $line=~/^\[File\](.*)/;
                $in_cont=1 if $line=~/^\[Content Begin\]/;
                $line="";
        }

}

close(IN);

$start=$num-9 if(not $start);

my $i=0;
for($i=0;$i<$num;$i++){

	if($i+1>=$start and $i<=$start+10 ){
		$final_str=$msg_list[$i].$final_str;
	}

}



if($start+10<=$num){
	$new_start=$start+10;
	$final_str.=<<EOF;
	<a href="?start=$new_start">New pages </a>&nbsp;&nbsp;
EOF
}
if($start >0){
	$new_start = $start-10;
	$new_start=1 if $new_start<=0;
	$final_str.=<<EOF;
	<a href="?start=$new_start">Old pages </a> &nbsp;&nbsp;
EOF
}

	return $final_str;

}


sub m0_output()
{
        my ($num,$mfrom,$mdate,$mcontent)=@_;

        $mcontent=~s/\n/<br>/g;
        $mcontent=~s/\s\s/\&nbsp;\&nbsp;/g;

return <<EOF;
	[$num] $mfrom on $mdate<br>
        <span class="msg_text">$mcontent</span>
	<hr width="80%" align="left" size=1>
EOF

}




sub m_output()
{
        my ($num,$mfrom,$mdate,$mcontent)=@_;

        $mcontent=~ s/\r\n/<br>/g;
        $mcontent=~ s/\r/<br>/g;
        $mcontent=~s/\s\s/\&nbsp;\&nbsp;/g;

return <<EOF;
<table border="0" width="600">
        <tr width="20"  align="left">
                <td>
		[$num] From: $mfrom
                </td>
                <td>Date: $mdate
                </td>
        </tr>
        <tr>
                <td colspan="2">
                <span class="msg_text">$mcontent</span>
                </td>
        </tr>
</table>
<hr width="80%" align="left">
EOF


}




sub send_email(){

	my ($user_email,$user_name,$link,$g_id)=@_;
	
	my $email_msg=<<EOF;

Hi, $user_name, 

  Thanks for using "Ship It"! 

  Here is the link for your uploaded file(s).

  $link

  Now, you can tell your friends the link above to share the files.

  I will be glad to get any advice from you!


--------------------------------------
    Peak, from Ship It.
    Email: xfliu.math\@gmail.com
    Our Life in JP: http://jp-life.org
--------------------------------------

EOF
	use MIME::Lite;
	my $mailfrom="Ship It <shipit\@jp-life.org>";
	my $mailto="$user_email, shipit_confirm\@jp-life.org";
	my $subject="Your id for downloading file from ShipIt [$g_id]";
	my $msg = MIME::Lite->new( From =>$mailfrom, To =>$mailto, Subject =>"$subject", Type => 'multipart/mixed');
	$msg->attach( Type => 'text/plain; charset="utf-8"', Data => "$email_msg");
	$msg->send();
}


sub ftp_delete(){
	my ($add,$user,$pwd,$localf)=@_;
	use Net::FTP;

    $ftp = Net::FTP->new("$add", Debug => 0);
#      or die "Cannot connect to xfliu.web.fc2.com: $@";

    $ftp->login($user,$pwd);
#      or die "Cannot login ", $ftp->message;

    $ftp->cwd("download");
#      or die "Cannot change working directory ", $ftp->message;

    $ftp->delete($localf);
#      or die "get failed ", $ftp->message;

	$ftp->quit;
	
}


sub ftp_upload(){
	my ($add,$user,$pwd,$localf,$remotef)=@_;
	
	use Net::FTP;

    $ftp = Net::FTP->new("$add", Debug => 0);
#      or die "Cannot connect to xfliu.web.fc2.com: $@";

    $ftp->login($user,$pwd);
#      or die "Cannot login ", $ftp->message;

    $ftp->cwd("download");
#      or die "Cannot change working directory ", $ftp->message;

    $ftp->binary;
    $ftp->put($localf,$remotef);
#      or die "get failed ", $ftp->message;

	$ftp->quit;

}
sub get_space()
{
	my ($key)=@_;
	my $total_size=0;
	open(FH, "<server.config");
	while(<FH>){

		s/\///g;
		my @elements = split (/\|/, $_);
		my $size=$elements[2];
		if(/$key/ and $key){
		  $total_size=$total_size+$size;
		}
		if(not $key){
		  $total_size=$total_size+$size;
		}
        }
	return $total_size;
}
sub used_space()
{
	my ($key)=@_;
	remove_old();

	my @files=group_files("");
	my $total_size=0;
	foreach(@files){
		s/\///g;
		my @elements = split (/\|/, $_);
		my $size=$elements[3];
		if(/$key/ and $key){
		  $total_size=$total_size+$size;
		}
		if(not $key){
		  $total_size=$total_size+$size;
		}
        }
	return $total_size;
}

sub remove_old(){

	my @files=open_files();
	my @newfiles;
	my $dead_line=get_deadline();

	my $old_record;
	foreach(@files){
		my @elements = split (/\|/, $_); 
		my $fday=$elements[5];
		$fday=~/^(.+):/;
		$fday=$1;
		if($fday<$dead_line and $fday){
		   $old_record.=$_;
		   unlink($elements[1]);
		   $report.="<li>File $elements[1] deleted.\n";
		}else{
	 		push(@newfiles ,$_);
		}
	}
	if($old_record){
		save_files(@newfiles);	
		open(FH,">>old_file");
		print FH $old_record;
		close(FH);
	}

	my @groups=open_groups();
	my @newgroups;
	my $old_record;
	foreach(@groups){
		my @elements = split (/\|/, $_); 
		my $gday=$elements[3];
		$gday=~/^(.+):/;
		$gday=$1;
		if($gday<$dead_line and $gday){
		   $old_record.=$_;
		   $report.="<li>Group $elements[1] deleted.\n";
		}else{
	 		push(@newgroups ,$_);
		}
	}
	if($old_record){
		save_groups(@newgroups);	
		open(FH,">>old_group");
		print FH $old_record;
		close(FH);
	}
}

sub put_cookie {
#&put_cookie($cookie_name,$cookie_on_days,$cookie_data,$cookie_path);

	my($cookie_name,$cookie_on_days,$cookie_data,$cookie_path) = @_;
	my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst,$month,$youbi,$date_gmt);
	$ENV{'TZ'} = "GMT";
	($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time + $cookie_on_days * 24 * 60 * 60);
	$month = ('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec')[$mon];
	$youbi = ('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday')[$wday];
	$date_gmt = sprintf("%s\, %02d\-%s\-%04d %02d:%02d:%02d GMT",$youbi,$mday,$month,$year + 1900,$hour,$min,$sec);
	print "Set-Cookie: $cookie_name=$cookie_data; expires=$date_gmt; path=$cookie_path\n";
}

sub get_deadline()
{
      my $days=6;
      my @c_d=localtime(time-$days*24*3600);
	   my ($cdh,$cdmin,$cds)=(@c_d[2],@c_d[1],@c_d[0]);
	   my ($cdy,$cdm,$cdd)=(@c_d[5],@c_d[4],@c_d[3]);
	   $cdm=$cdm+1;
	   $cdy=$cdy-100+2000;
	   
	   $cdh="0".$cdh if $cdh<10;
	   $cdmin="0".$cdmin if $cdmin<10;
	   $cds="0".$cds if $cds<10;

	   $cdm="0".$cdm if $cdm<10;
	   $cdd="0".$cdd if $cdd<10;
	   
	   return "$cdy$cdm$cdd";
}
sub get_date()
{
      my ($days)=@_;
      my $seconds=0;
      $seconds=
      my @c_d=localtime(time+$seconds);
	   my ($cdh,$cdmin,$cds)=(@c_d[2],@c_d[1],@c_d[0]);
	   my ($cdy,$cdm,$cdd)=(@c_d[5],@c_d[4],@c_d[3]);
	   $cdm=$cdm+1;
	   $cdy=$cdy-100+2000;
	   
	   $cdh="0".$cdh if $cdh<10;
	   $cdmin="0".$cdmin if $cdmin<10;
	   $cds="0".$cds if $cds<10;

	   $cdm="0".$cdm if $cdm<10;
	   $cdd="0".$cdd if $cdd<10;
	   
	   return "$cdy$cdm$cdd:$cdh$cdmin$cds";
}


sub create_group()
{
	my($g_id,$u_name,$g_title) = @_;

	open(FH,">>grouplist");
	my $mydate=get_date();
	print FH "$g_id\|$g_title\|$u_name\|$mydate\n";
	close FH;
	return $g_id; 
} 

sub save_groups() { 
	my @groups = @_;
	open(FH,">grouplist");
	foreach(@groups) { print FH $_; } 
	close FH; 
}
sub save_files(){
	my @files = @_; 
	open(FH,">filelist"); 
	foreach(@files){
		print FH $_; 
	}
	close FH; 
} 

sub open_groups()
{	
	my ($key)=@_;
	my @groups;
	my $i=0;
	open(FH, "grouplist");
	while(<FH>){
		$groups[$i++] = $_ if  /$key/ or not $key;
	}	
	close FH;
	return @groups;
}

sub open_files()
{
	my ($key)=@_;
	my @files;
	my $i=0;
	open(FH, "filelist");
	while(<FH>){
		$files[$i++]=$_ if /$key/ or not $key;
	}	
	close FH;
	return @files;
}

sub group_files()
{
	my($t_g_id) = @_;
	my @files;
	my $i=0;
	open(FH, "filelist");
	while(<FH>){
		if(/$t_g_id/ and $t_g_id){
			$files[$i]=$_;
			$i++;
		}
		if(not $t_g_id){
			$files[$i]=$_;
			$i++;
		}
	}	
	close FH;
	
	return @files;
}

sub create_name()
{
	my $i;
	my $str;
	
	for($i=1;$i<=5;$i++){
		$str.=chr(int(rand(26))+65);
	}
	return $str;
}

sub create_num()
{
	my $i;
	my $str;
	
	for($i=1;$i<=6;$i++){
		$str.=int(rand(9));
	}
	return $str;
}

sub num_format()
{
	my ($v,$f)=@_;
	if(not $f )
	{
		$f="G" if $v>=1000000000;
		$f="M" if $v>=500000 and $v <1000000000;
		$f="K" if $v<500000;
	}
	if($f eq "G"){
	$v=$v/1000000000;
	$v=int($v*1000)/1000;
	$v = $v. " Giga";
	}
	if($f eq "M"){
	$v=$v/1000000;
	$v=int($v*1000)/1000;
	$v = $v. " Mega";	
	}
	if($f eq "K"){
	$v= $v/1000;
	$v = $v. " Kbyte";	
	}
	return $v;
	
}
1;
